package voja.android.log;

import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.CallLog.Calls;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.TextView;
import voja.android.log.Util;

public class MainActivity extends Activity {
	private static final String ROW_SEPARATOR = new Character((char)13).toString();
	private static final String COL_SEPARATOR = new Character((char)9).toString();
	private static final String DATA_FILENAME = "callog.csv";
	private static final String DATA_CONTENT_TYPE = "text/csv";
	private static final String NO_NAME = "Unknown";
	
	public String filename="";
	
	String[] call_fields = {
			Calls.NUMBER,
			Calls.TYPE,
			Calls.CACHED_NAME,
			Calls.CACHED_NUMBER_LABEL,
			Calls.DATE,
			Calls.DURATION
	};
	String call_orderBy = Calls.DATE + " DESC";
	
	String[] sms_fields = {
		"address", "person", "date" 
	};
	String sms_orderBy = "date DESC";
	
	Cursor cur;
	String data_calls="", data_sms="";
	
	long callsPlaced=0;
	long callsReceived=0;
	long callsMissed=0;
	static long dateFirst=-1, dateLast=-1;
	
	TextView er, callCount, smsCount;
	TextView btnOptions;
	TextView btnDownloadCalls;
	TextView btnDownloadSMS;
	
	SmsManager sms;
	Context context;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		callCount = (TextView)findViewById(R.id.callCount);
		smsCount = (TextView)findViewById(R.id.smsCount);
		er = (TextView)findViewById(R.id.error);
		er.setVisibility(View.INVISIBLE);
		sms = SmsManager.getDefault();
		context = findViewById(R.id.Container).getContext();
		
		btnDownloadCalls = (TextView)findViewById(R.id.btnDownloadCalls);
		btnDownloadSMS = (TextView)findViewById(R.id.btnDownloadSMS);
		btnOptions = (TextView)findViewById(R.id.btnSettings);
		btnOptions.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MainActivity c = (MainActivity)v.getContext();
				Intent intent = new Intent(MainActivity.this, ExpandableFilter.class);
				intent.putExtra("date_first", "" + c.dateFirst);
				intent.putExtra("date_last", "" + c.dateLast);
				startActivity(intent);
			}
		});
		
		loadCalls();
		loadSMS();
	}
	
	public void loadCalls(){
		cur = getContentResolver().query(Calls.CONTENT_URI, call_fields, null, null, call_orderBy);
		
		if(cur.moveToFirst()){
			data_calls += Util.join(call_fields, COL_SEPARATOR);
			int type;
			int count=0;
			String date="";
			
			do{
				count++;
				type = cur.getInt(1);
				
				long d = cur.getLong(4);
				date = Util.dateFromTimestamp(d, "yyyy-MM-dd hh:mm:ss");
				
				if(dateFirst<0 || dateFirst>d) dateFirst = d;
				if(dateLast<0 || dateLast<d) dateLast = d;
				
				if(type==Calls.OUTGOING_TYPE) callsPlaced += cur.getLong(5);
				if(type==Calls.INCOMING_TYPE) callsReceived += cur.getLong(5);
				if(type==Calls.MISSED_TYPE) callsMissed += 1;
				
				data_calls += ROW_SEPARATOR +
						cur.getString(0) + COL_SEPARATOR +
						Util.getType(type) + COL_SEPARATOR +
						cur.getString(2) + COL_SEPARATOR +
						cur.getString(3) + COL_SEPARATOR +
						date + COL_SEPARATOR +
						cur.getString(5);
			}while(cur.moveToNext());
			
			try {
				filename = Environment.getExternalStorageDirectory() + "/" + DATA_FILENAME;
				File f = new File(filename);
				
				FileOutputStream output = new FileOutputStream(f);
				output.write(data_calls.getBytes());
				output.close();
				
				callCount.setText(""+count);
				
				TextView tmp;
				tmp = (TextView)findViewById(R.id.outValue);				
				tmp.setText(Util.timeFormat(callsPlaced));

				tmp = (TextView)findViewById(R.id.inValue);				
				tmp.setText(Util.timeFormat(callsReceived));
				
				tmp = (TextView)findViewById(R.id.missedValue);				
				tmp.setText("" + callsMissed);
				
				tmp = (TextView)findViewById(R.id.date_start);
				tmp.setText(Util.dateFromTimestamp(dateFirst, "dd.MMM yyyy"));
				
				tmp = (TextView)findViewById(R.id.date_end);
				View delimiter = findViewById(R.id.date_delimiter);
				
				int sd = Integer.parseInt(Util.dateFromTimestamp(dateFirst, "d"));
				int sm = Integer.parseInt(Util.dateFromTimestamp(dateFirst, "M"));
				int sy = Integer.parseInt(Util.dateFromTimestamp(dateFirst, "y"));
				int ed = Integer.parseInt(Util.dateFromTimestamp(dateLast, "d"));
				int em = Integer.parseInt(Util.dateFromTimestamp(dateLast, "M"));
				int ey = Integer.parseInt(Util.dateFromTimestamp(dateLast, "y"));
				int test = sd-ed + sm-em + sy-ey;
				
				if(test != 0){
					tmp.setText(Util.dateFromTimestamp(dateLast, "dd.MMM yyyy"));
					tmp.setVisibility(View.VISIBLE);
					delimiter.setVisibility(View.VISIBLE);
				}else{
					tmp.setVisibility(View.GONE);
					delimiter.setVisibility(View.GONE);
				}
				
				btnDownloadCalls.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						MainActivity c = (MainActivity)v.getContext();
						File f = new File(c.filename);
						
						try{
							Intent intent = new Intent();
							intent.setAction(Intent.ACTION_VIEW);
							intent.setDataAndType(Uri.fromFile(f), DATA_CONTENT_TYPE);
							startActivity(intent);
						}catch(Exception e){
							Util.error(c, e.getMessage());
						}
					}
				});
				
			} catch (Exception e) {
				Util.error(this, e.getMessage());
			}
		}else{
			callCount.setText("0");
			findViewById(R.id.date_delimiter).setVisibility(View.INVISIBLE);
		}
	}

	public void loadSMS(){
		String[] uris = {"content://sms/inbox", "content://sms/sent"};
		int[] ids = {R.id.receivedValue, R.id.sentValue};
		int count=0;
		ContentResolver cr = getContentResolver();
		Uri u;
		
		for(int i=0; i<uris.length; i++){
			u = Uri.parse(uris[i]);
			try{
				cur = cr.query(u, sms_fields, null, null, sms_orderBy);
				count += cur.getCount();
				TextView txtIn = (TextView)findViewById(ids[i]);
				txtIn.setText("" + cur.getCount());
			}catch(Exception e){
				Util.error(this, e.getMessage());
			}
		}
		if(count > 0){
			btnDownloadSMS.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					MainActivity c = (MainActivity)v.getContext();
					if(c.fillSMSData()){
						try{
							filename = Environment.getExternalStorageDirectory() + "/" + DATA_FILENAME;
							File f = new File(filename);
							
							FileOutputStream output = new FileOutputStream(f);
							output.write(data_sms.getBytes());
							output.close();
							
							Intent intent = new Intent();
							intent.setAction(Intent.ACTION_VIEW);
							intent.setDataAndType(Uri.fromFile(f), DATA_CONTENT_TYPE);
							startActivity(intent);
						}catch(Exception e){
							Util.error(c, e.getMessage());
						}
					}
				}
			});
		}
		smsCount.setText(""+count);
	}
	
	public Boolean fillSMSData(){
		Boolean ret = false;
		data_sms = "";
		try{
			cur = getContentResolver().query(Uri.parse("content://sms/"), sms_fields, null, null, sms_orderBy);
			if(cur.moveToFirst()){
				data_sms = "Number" + COL_SEPARATOR +
							"Name" + COL_SEPARATOR +
							"Date" + COL_SEPARATOR +
							"Type";
				String name = cur.getString(1);
				long d = cur.getLong(2);
				do{
					data_sms += ROW_SEPARATOR +
							cur.getString(0) + COL_SEPARATOR +
							(name==null ? NO_NAME : name) + COL_SEPARATOR +
							Util.dateFromTimestamp(d, "yyyy-MM-dd hh:mm:ss");
				}while(cur.moveToNext());
				ret = true;
			}else{
				Util.error(this, "Error moving to first");
			}
		}catch(Exception e){
			Util.error(this, e.getMessage());
			ret = false;
		}
		
		return ret;
	}
}